package com.example.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 一个简单的客户端，用于向{@link GreeterServer}请求问候。
 */
public class GreeterClient {
  private static final Logger logger = Logger.getLogger(GreeterClient.class.getName());

  private final ManagedChannel channel;
  private final GreeterGrpc.GreeterBlockingStub blockingStub;

  /** 构造连接到{@code host:port}上HelloWorld服务器的客户端。 */
  public GreeterClient(String host, int port) {
    this(ManagedChannelBuilder.forAddress(host, port)
        // 通道默认是安全的（通过SSL/TLS）。在本示例中，我们禁用TLS以避免
        // 需要证书。
        .usePlaintext()
        .build());
  }

  /** 使用现有通道构造访问HelloWorld服务器的客户端。 */
  GreeterClient(ManagedChannel channel) {
    this.channel = channel;
    blockingStub = GreeterGrpc.newBlockingStub(channel);
  }

  public void shutdown() throws InterruptedException {
    channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  }

  /** 向服务器问好。 */
  public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    try {
      response = blockingStub.sayHello(request);
    } catch (StatusRuntimeException e) {
      logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
      return;
    }
    logger.info("Greeting: " + response.getMessage());

    try {
      response = blockingStub.sayHelloAgain(request);
    } catch (StatusRuntimeException e) {
      logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
      return;
    }
    logger.info("Greeting again: " + response.getMessage());
  }

  /**
   * 向服务器问好。如果提供了参数，{@code args}的第一个元素将用作问候中的名称。
   */
  public static void main(String[] args) throws Exception {
    GreeterClient client = new GreeterClient("localhost", 50051);
    try {
      String user = "world";
      // 如果提供了参数，则使用该参数作为要问候的名称
      if (args.length > 0) {
        user = args[0];
      }
      client.greet(user);
    } finally {
      client.shutdown();
    }
  }
}